package com.zhiwang.planet.ui

import android.Manifest
import android.annotation.SuppressLint
import android.app.AlertDialog
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.wifi.WifiManager
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.telephony.SubscriptionInfo
import android.telephony.SubscriptionManager
import android.telephony.TelephonyManager
import android.text.SpannableString
import android.text.Spanned
import android.text.TextPaint
import android.text.TextUtils
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.util.Log
import android.view.View
import android.view.inputmethod.InputMethodManager
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.tencent.mm.opensdk.modelmsg.SendAuth
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import com.zhiwang.planet.App
import com.zhiwang.planet.BuildConfig
import com.zhiwang.planet.R
import com.zhiwang.planet.aop.net.NetWorkRequired
import com.zhiwang.planet.di.component.DaggerLoginComponent
import com.zhiwang.planet.di.module.AccountModule
import com.zhiwang.planet.di.module.AutoDisposeModule
import com.zhiwang.planet.event.DestroyLoginActivity
import com.zhiwang.planet.event.LoginEvent
import com.zhiwang.planet.mvp.p.LoginLogoutPresenter
import com.zhiwang.planet.mvp.p.UserPresenter
import com.zhiwang.planet.mvp.v.CheckBindWxView
import com.zhiwang.planet.mvp.v.LoginView
import com.zhiwang.planet.mvp.v.WxLoginView
import com.zhiwang.planet.mvvm.model.entity.User
import com.zhiwang.planet.mvvm.model.entity.main.BindBody
import com.zhiwang.planet.ui.my.ModifyPasswordActivity
import com.zhiwang.planet.ui.my.RegisterActivity
import com.zhiwang.planet.util.*
import kotlinx.android.synthetic.main.activity_login.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import javax.inject.Inject

/**
 * A login screen that offers login via email/password.
 */
class LoginActivity : BaseActivity(), LoginView, CheckBindWxView, WxLoginView, MiitHelper.AppIdsUpdater {

    private val TAG = "LoginActivity"

    companion object {
        fun start(context: Context) {
            EventBus.getDefault().post(DestroyLoginActivity)
            context.startActivity(Intent(context, LoginActivity::class.java))
        }
    }


//    @Inject
//    lateinit var networkViewModel: NetWorkViewModel

    @Inject
    lateinit var loginPresenter: LoginLogoutPresenter

    @Inject
    lateinit var userPresenter: UserPresenter

    var oaidWating = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)
        setSupportActionBar(toolbar)
        var loginComponent = DaggerLoginComponent
                .builder()
                .name(TAG)
                .appComponent((application as App).appComponent)
                .accountModule(AccountModule(this))
                .autoDisposeModule(AutoDisposeModule(this))
                .build()
        loginComponent
                .inject(this)
        loginPresenter.loginView = this
        userPresenter.wxLoginView = this
        userPresenter.checkBindWxView = this

        Utils.setStatusBar(this, false, false)

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_PHONE_STATE)
            ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.READ_PHONE_STATE), 1200)
        } else getDeviceId()

        getDeviceId()
        userPresenter.checkEverInstallOnThisDevice(deviceId ?: "", ::onDeviceQueryResult)
        EventBus.getDefault().register(this)


        if (BuildConfig.DEBUG){
            toolbar.setOnLongClickListener {
                val env = AppHelper.switchEnv()
                if (env) {
                    Toaster.message("已经切换到测试环境，关闭app 后重进后即可生效")
                } else {
                    Toaster.message("已经切换到外网线上环境，关闭app 后重进后即可生效")
                }
                TokenManager.clearToken()
                return@setOnLongClickListener true
            }
        }

        val spanned = SpannableString("登录即代表阅读并同意《隐私服务协议》和《服务协议》")
        spanned.setSpan(object: ClickableSpan(){

            override fun onClick(widget: View) {
                quickStartActivity(PrivacyActivity::class.java)
            }
            override fun updateDrawState(ds: TextPaint) {
                ds.linkColor = ContextCompat.getColor(this@LoginActivity,R.color.md_material_blue_600)
                super.updateDrawState(ds)
            }

        }, 10, 18, Spanned.SPAN_INCLUSIVE_INCLUSIVE)

        spanned.setSpan(object: ClickableSpan(){

            override fun onClick(widget: View) {
                WebViewActivity.load(this@LoginActivity,Store.USER_AGREEMENT)
            }

            override fun updateDrawState(ds: TextPaint) {
                ds.linkColor = ContextCompat.getColor(this@LoginActivity,R.color.md_material_blue_600)
                super.updateDrawState(ds)
            }

        }, 19, 25, Spanned.SPAN_INCLUSIVE_INCLUSIVE)
        privacy_btn.text = spanned
        privacy_btn.movementMethod = LinkMovementMethod.getInstance()
        privacy_btn.setTextIsSelectable(false)

    }


    var imeiCheckedIndex = -1

    @SuppressLint("MissingPermission")
    private fun prepareMultiImeiChooser(): Boolean {

        val deviceIdList = arrayListOf<String>()

        val telecomManager = getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
            val subscriptionManager = getSystemService(TELEPHONY_SUBSCRIPTION_SERVICE) as SubscriptionManager
            val activeSubscriptionInfoList: List<SubscriptionInfo>? = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                subscriptionManager.accessibleSubscriptionInfoList
            } else {
                subscriptionManager.activeSubscriptionInfoList
            }
            activeSubscriptionInfoList?.forEach {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
                    deviceIdList.add(telecomManager.getImei(it.simSlotIndex))
            }

            if (activeSubscriptionInfoList == null || activeSubscriptionInfoList.isEmpty()) {

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    telecomManager.getImei(0)?.apply {
                        deviceIdList.add(this)
                    }
                    telecomManager.getImei(1)?.apply {
                        deviceIdList.add(this)
                    }


                }
            }

        }

        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.P) deviceIdList.add(Settings.Secure.getString(contentResolver, Settings.Secure.ANDROID_ID))

        AlertDialog.Builder(this, R.style.NormalDialogTheme)
                .setTitle("选择您要登录的设备号")
                .setMultiChoiceItems(deviceIdList.toTypedArray(), BooleanArray(deviceIdList.size) { it == imeiCheckedIndex }) { dialog, which, isChecked ->
                    deviceId = deviceIdList[which]
                    Toaster.message("你已选择设备号：${deviceIdList[which]}")
                    imeiCheckedIndex = which
                    dialog.dismiss()
                }
                .create()
                .show()

        return true
    }

    fun onDeviceQueryResult(visible: Boolean) {
        if (visible.not()) {
            tv_other_login_means.isEnabled = false
            iv_wx_login_btn.isEnabled = false
            tv_other_login_means.setInvisible()
            iv_wx_login_btn.setInvisible()
        }
    }

    @NetWorkRequired
    fun login(v: View) {
        val wifiManager = applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager

        var wifiName = wifiManager.connectionInfo?.ssid ?: ""

        if (wifiName.indexOf("\"") == 0 && wifiName.lastIndexOf("\"") == wifiName.lastIndex)
            wifiName = wifiName.substring(1, wifiName.lastIndex)

        val phone = name.text.toString()
        val pwd = password.text.toString()
        if (TextUtils.isEmpty(deviceId)) {
            Toaster.message("无法获取您的设备号,请在应用管理中授予权限")
            return
        } else {
            if (deviceId != null)
                loginPresenter.login(phone, pwd, deviceId!!, wifiName)
            else oaidWating = true
        }
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == 1200) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                getDeviceId()
            }
        }

    }

    var deviceId: String? = null
    @SuppressLint("MissingPermission", "HardwareIds")
    fun getDeviceId() {

        deviceId = "无法获取设备号"
        val telecomManager = getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
        deviceId = when {
            Build.VERSION.SDK_INT > Build.VERSION_CODES.P -> {
                // oaid for android 10
                retrieveOAIDForAndroidQ()
                return
            }

            //old deviceid
            TextUtils.isEmpty(telecomManager.deviceId).not() -> {
                if (BuildConfig.DEBUG)
                    Toaster.message("step1${Build.VERSION.SDK_INT}")
                telecomManager.deviceId
            }


            // imei
            Build.VERSION.SDK_INT >= Build.VERSION_CODES.O -> retrieveImeiExcludeMeid(telecomManager)


            //failing
            else -> "获取设备码失败orz"
        }
        deviceId?.apply { TokenManager.saveDevice(this) }
    }


    @SuppressLint("NewApi", "MissingPermission")
    private fun retrieveImeiExcludeMeid(telecomManager: TelephonyManager): String {


        val meid0 = telecomManager.getMeid(0) ?: ""
        val meid1 = telecomManager.getMeid(1) ?: ""

        if (BuildConfig.DEBUG)
            Log.i(TAG, "meids--: 0:->$meid0   1:->$meid1")

        val meid = if (TextUtils.isEmpty(meid0)) meid1 else meid0


        val imei0 = telecomManager.getImei(0)
        val imei1 = telecomManager.getImei(1)

        if (BuildConfig.DEBUG)
            Log.i(TAG, "imeis: 0:->$imei0   1:->$imei1")

        val imei = when {
            TextUtils.isEmpty(meid) -> imei0
            TextUtils.equals(meid, imei0) -> imei1
            else -> imei0
        }
        return imei
    }

    private fun retrieveOAIDForAndroidQ() {
        deviceId = deviceId.plus(" android 10;请尝试退出账号后重新登录")
        MiitHelper(this).getDeviceIds(this)
    }


    override fun OnIdsAvalid(ids: String) {

        deviceId = ids
        deviceId?.apply { TokenManager.saveDevice(this) }
        if (oaidWating) {
            login(login_btn)
        }
    }

    override fun OnIdsError(msg: String?) {
        deviceId = msg
    }



    override fun onLogin(user: User) {
        closeIme()
        Toaster.message(R.string.login_success)
        EventBus.getDefault().post(LoginEvent())
        suicideAfterTransition()
    }

    fun closeIme() {
        val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(window.decorView.windowToken, 0)
    }

    fun forgotPassword(v: View) {
        quickStartActivity(ModifyPasswordActivity::class.java)
        suicideAfterTransition()
    }

    fun register(v: View) {
        quickStartActivity(RegisterActivity::class.java)
        suicideAfterTransition()
    }

    override fun onSupportNavigateUp(): Boolean {
        onBackPressed()
        return super.onSupportNavigateUp()
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun shouldDestroyLoginActivity(event: DestroyLoginActivity) {
        finish()
    }

    fun tryWxLogin(view: View) {
        val api = WXAPIFactory.createWXAPI(this, Store.APP_ID, false)
        api.registerApp(Store.APP_ID)
        val req = SendAuth.Req()
        req.scope = "snsapi_userinfo"
        req.state = "none"
        if (req.checkArgs()) {
            api.sendReq(req)
        }
    }


//    @Subscribe(threadMode = ThreadMode.MAIN)
//    fun onWxLogin(e: WxLoginEvent) {
//        userPresenter.checkWxBind(e.code, deviceId ?: "")
//    }

    override fun onCheckWxBind(bindBody: BindBody) {
        if (bindBody.bind == 1) {
            TokenManager.saveToken(bindBody.token)
            if (BuildConfig.DEBUG)
                Toaster.message("已绑定微信")
            userPresenter.getUserInfo()
        } else {

            suicideAfterTransition()
            //未绑定跳转，让用户选择绑定老用户，或者 一键生成新用户
//            BindPhoneActivity.start(context = this, code = bindBody.openid)
        }
    }

}

